from django.db import models

# Create your models here.

class Suburb(models.Model):
    post_code = models.CharField(maxlength=100, primary_key=True)   
    suburb = models.CharField(maxlength=100)
    def __str__(self):
        return self.post_code
    class Admin:
        pass

class Contact(models.Model):
    first_name = models.CharField(maxlength=30)
    last_name = models.CharField(maxlength=20)
    address = models.CharField(maxlength=200)
    suburb = models.CharField(maxlength=40)
    state = models.USStateField()
    country = models.CharField(maxlength=40)
    email = models.EmailField()
    date_added = models.DateTimeField()
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using __unicode__ here rather than __str__.
        """
        return "%s %s" % (self.first_name, self.last_name) 
    
    def get_my_phones(self):
        return self.phone_set.iterator()
    
    def get_my_contact_types(self):
        """
        Return a list of which 'types' this contact belongs to - ie recipient, 
        volunteer, etc 
        """
        ## Django gives each model/table some info about *reverse*
        ## lookups as well as the more obvious forward lookups. So, in other 
        ## words, it provides some info about *who is foreign-keying into us*, 
        ## as well as who we are foreign-keying into.
        ## What we want to do in this particular case is find out which, if
        ## any, of the other contact 'types' are keying into us. 
        my_contact_types = []
        ## Are we a volunteer?
        if self.volunteer_set.count():
            my_contact_types.append('volunteer')
        ## Are we a recipient?
        if self.recipient_set.count():
            my_contact_types.append('recipient')
        ## Are we a group?
        if self.group_set.count():
            my_contact_types.append('group')
        ## Otherwise, we are unspecified
        if not my_contact_types:
             my_contact_types.append('unspecified')    
        return my_contact_types
    get_my_contact_types.short_description = "Contact Type"
    
    def get_my_phone_number_ids(self):
        """
        Return a list of the ids of phone-numbers belonging to this contact.
        """
        ## Django gives each model/table some info about *reverse*
        ## lookups as well as the more obvious forward lookups. So, in other 
        ## words, it provides some info about *who is foreign-keying into us*, 
        ## as well as who we are foreign-keying into.
        ## What we want to do in this particular case is find out which, if
        ## any, of the entries in the Phone table are keying into us.
        if self.phone_set.count():
            phone_ids = [cp.phone_id for cp in self.phone_set.iterator()]
        else:
            phone_ids = None       
        return phone_ids
    get_my_phone_number_ids.short_description = "Phone Number Ids"

    def get_my_phone_numbers(self):
        """
        Return a list of tha actual phone-numbers belonging to this contact.
        """
        ## Django gives each model/table some info about *reverse*
        ## lookups as well as the more obvious forward lookups. So, in other 
        ## words, it provides some info about *who is foreign-keying into us*, 
        ## as well as who we are foreign-keying into.
        ## What we want to do in this particular case is find out which, if
        ## any, of the entries in the Phone table are keying into us.

        phone_ids = self.get_my_phone_number_ids()
        if phone_ids: 
            phone_objects = Phone.objects.filter(pk__in=phone_ids)
        else:
            phone_objects = None            
        return phone_objects
    get_my_phone_numbers.short_description = "Phone Number(s)" 
    
    class Meta:
        """ Model metadata is 'anything that is not a field', such as 
        ordering options, etc. """
        ## Avoid the ugly 'contactss' in the admin interface.
        verbose_name_plural = "Contacts"
        
    class Admin:
        ## What columns will we display in the change-list page?
        list_display = ('__str__', 'get_my_contact_types', 'address', 'suburb')
        
        """Set list_filter to activate filters in the right sidebar of the 
        change list page of the admin. This should be a list of field names, 
        and each specified field should be either a 
        BooleanField, CharField, DateField, DateTimeField, IntegerField or 
        ForeignKey."""
        list_filter = ('address', 'suburb', 'first_name', 'id')
        
        
        search_fields = ('suburb', 'first_name')
        ## How will the fieldsets be set-up on the actual add/edit page for an
        ## individual item?
        fields = (
        (None, {
            'fields': ('first_name', 'last_name')
        }),
        ('Address Details', {
            'classes': 'collapse',
            'fields' : ('address', 'suburb', 'state', 'country', 'email')
        }),
        ('Date', {
            'fields': ('date_added',)
        })
                    )	
##---------------------------
  
class Group(models.Model):
    OS_CHOICES = (
        ('linux', 'Linux'),
        ('windows', 'Windows'),
    )   
    group_name = models.CharField(maxlength=100)
    contact_person = models.ForeignKey(Contact)
    contact_position_in_organisation = models.CharField(maxlength=50)
    ## Consider using DecimalField if we upgrade to more modern version of 
    ## Django.
    financial_position = models.FloatField(max_digits=10, decimal_places=2)
    staff_numbers = models.IntegerField()
    volunteer_numbers = models.IntegerField()
    who_will_use_computers = models.CharField(maxlength=50)
    computers_used_for = models.CharField(maxlength=50)
    need_network = models.BooleanField()
    linux_or_windows = models.CharField(maxlength=7, choices=OS_CHOICES)
    training_needed = models.BooleanField()
    #person_in_charge_of_computers = models.ForeignKey(Contact)
    feedback_yes_no = models.BooleanField()
    ## Consider using DecimalField if we upgrade to more modern version of 
    ## Django.
    installation_charge = models.FloatField(max_digits=10, decimal_places=2)
    cost_of_request = models.FloatField(max_digits=10, decimal_places=2)
    
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using unicode here rather than str.
        """
        return self.group_name 
    class Meta:
        """ Model metadata is 'anything that is not a field', such as 
        ordering options, etc. """
        ## Avoid the ugly 'contactss' in the admin interface.
        verbose_name_plural = "Groups"
    class Admin:
        pass
    
class GroupService(models.Model):
    SERVICE_TYPES = (
        ('outreach', 'Outreach'),
        ('community', 'Community'),
        ('educational', 'Educational'),
        ('other', 'Other'),
    )  
    group = models.ForeignKey(Group) 
    service_name = models.CharField(maxlength=20)
    service_type = models.CharField(maxlength=11, choices=SERVICE_TYPES)
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using unicode here rather than str.
        """
        my_group = Group.objects.get(pk=self.group)
        return "%s (%s) provided by %s." % (service_name, service_type, 
            my_group.group_name) 
    class Meta:
        """ Model metadata is 'anything that is not a field', such as 
        ordering options, etc. """
        ## Avoid the ugly 'contactss' in the admin interface.
        verbose_name_plural = "Group Services"
    class Admin:
        pass
    
class Language(models.Model):
    language_name = models.CharField(maxlength=50)
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using unicode here rather than str.
        """
        return "%s" % (self.language_name) 
    class Meta:
        """ Model metadata is 'anything that is not a field', such as 
        ordering options, etc. """
        ## Avoid the ugly 'contactss' in the admin interface.
        verbose_name_plural = "Language Names"
    class Admin:
        pass
       
class UserLanguage(models.Model):
    LANGUAGE_USE_CHOICES = (
                            
        ('spoken', 'Spoken'),
        ('read', 'Read'),
        ('written', 'Written'),
    )
    LANGUAGE_PREFERENCE_CHOICES = (
                                   
        ('primary', 'Primary'),
        ('secondary', 'Secondary'),
    )
    contact = models.ForeignKey(Contact)
    language_name = models.ForeignKey(Language)
    language_usage = models.CharField(maxlength=7, 
        choices=LANGUAGE_USE_CHOICES)
    language_preference = models.CharField(maxlength=9, 
        choices=LANGUAGE_PREFERENCE_CHOICES)
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using unicode here rather than str.
        """
        return "%s - %s(%s)" % (self.language_name, self.language_usage, 
            self.language_preference) 
    def contact_name(self):
        my_contact = Contact.objects.get(pk=self.contact_id)
        return "%s %s" % (my_contact.first_name, my_contact.last_name)       
    contact_name.short_description = "Name"
    
    class Meta:
        """ Model metadata is 'anything that is not a field', such as 
        ordering options, etc. """
        ## Avoid the ugly 'contactss' in the admin interface.
        verbose_name_plural = "User-Language Joins"
        ## We cannot have say, Fred speaks English as his primary language 
        ## *and* Fred speaks English as his secondary language, so the
        ## following three fields must be unique when taken together.
        #unique_together = (("contact", "language_name", "language_preference"),)
    class Admin:
        list_display = ('__str__', 'contact_name')


class Volunteer(models.Model):
    HOURS_CHOICES = (      
    ('monday_am', 'Monday Mornings'),
    ('monday_pm', 'Monday Afternoons'),
    ('tuesday_am', 'Tuesday Mornings'),
    ('tuesday_pm', 'Tuesday Afternoons'),
    )
    INTERESTS = (      
    ('front_desk', 'Front Desk'),
    ('build_room', 'Build Room'),
    ('training', 'Training'),
    ('administration', 'Administration'),
    ('other', 'Other'),
    )
    contact = models.ForeignKey(Contact)
    hours = models.CharField(maxlength=10, choices=HOURS_CHOICES)
    interests = models.CharField(maxlength=20, choices=INTERESTS)
    
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using unicode here rather than str.
        """
        me = Contact.objects.get(id=self.contact_id)
        return "%s %s " % (me.first_name, me.last_name) 
    def get_my_interests(self):
        ## <wsl> pretty crufty! Will eventually change so that interests are
        ## stored as an ENUM or something anyway...
        if type(self.interests) == type('string'):
            self.interests = [self.interests]
        interests_list=[]
        for interest in self.interests:
            interests_list.append(interest)
        return self.interests
    
    class Meta:
        """ Model metadata is 'anything that is not a field', such as 
        ordering options, etc. """
        ## Avoid the ugly 'contactss' in the admin interface.
        verbose_name_plural = "Volunteers"
    class Admin:
        pass


class Recipient(models.Model):
    CONCESSION_TYPES = (
        ('healthcare', 'Healthcare Card'),
        ('student', 'Student'),
        ('other', 'Other'),
    )   
    INTERNET_TYPES = (
        ('none', 'None'),
        ('broadband', 'Broadband'),
        ('dialup', 'Dialup'),
    )   
    contact = models.ForeignKey(Contact)
    concession_type = models.CharField(maxlength=10, choices=CONCESSION_TYPES)
    concession_checked_by = models.ForeignKey(Volunteer)
    referring_org = models.ForeignKey(Group, null=True)
    install_windows = models.BooleanField()
    stay_with_linux = models.BooleanField()
    survey_contact = models.BooleanField()
    have_not_used_a_computer = models.BooleanField()
    can_type_documents = models.BooleanField()
    can_use_keyboard_and_mouse = models.BooleanField()
    can_use_email = models.BooleanField()
    can_use_internet = models.BooleanField()
    has_attended_training = models.BooleanField()
    internet_type = models.CharField(maxlength=9, choices=INTERNET_TYPES)
    
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using unicode here rather than str.
        """
        my_contact = Contact.objects.get(id=self.contact_id)
        return "%s %s " % (my_contact.first_name, 
            my_contact.last_name) 
    class Meta:
        """ Model metadata is 'anything that is not a field', such as 
        ordering options, etc. """
        ## Avoid the ugly 'contactss' in the admin interface.
        verbose_name_plural = "Recipients"
    class Admin:
        pass

class Phone(models.Model):
    PHONE_CHOICES = (
        ('mobile', 'Mobile'),
        ('landline-home', 'Home'),
        ('landline-work', 'Work'),
        ('landline-other', 'Other'),
    )
    contact = models.ForeignKey(Contact)
    phone_number = models.PhoneNumberField()
    ## 'landline-other' is longest option needed to be stored at present, with
    ## a length of 14 characters.
    phone_type = models.CharField(maxlength=14, choices=PHONE_CHOICES)
    def __str__(self):
        """ 
        This is what will be shown in the Admin interface, amongst other 
        places. If we migrate to a later version of django, may want to look
        into using unicode here rather than str.
        """
        return "%s: %s " % (self.phone_type, self.phone_number)   
    class Admin:
        pass 

################################################################################
## Classes below here are deprecated
################################################################################

    
